#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
查询历史显示组件模块
显示查询历史记录
"""

import logging
from typing import Dict, List, Any, Optional
from datetime import datetime

from PySide6.QtCore import Qt, Signal, Slot
from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout,
                              QListWidget, QListWidgetItem, QMenu,
                              QLabel, QToolButton, QMessageBox, QTextEdit)
from PySide6.QtGui import QFont, QIcon, QColor, QAction

from core.query_manager import get_query_manager, QueryResult
from config.settings import settings
from core.i18n import tr


# 初始化日志记录器
logger = logging.getLogger("query_history")


class QueryHistoryWidget(QWidget):
    """查询历史显示组件类"""
    
    # 信号定义
    query_selected = Signal(str)  # 选中的查询文本
    query_executed = Signal(str)  # 执行查询
    query_copied = Signal(str)  # 复制查询
    
    def __init__(self, parent=None):
        """初始化查询历史显示组件
        
        Args:
            parent: 父窗口
        """
        super().__init__(parent)
        self.query_manager = get_query_manager()
        self._init_ui()
        
    def _init_ui(self):
        """初始化UI"""
        # 主布局
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        
        # 标题栏
        title_layout = QHBoxLayout()
        title_layout.setContentsMargins(0, 0, 0, 0)

        # 刷新按钮
        refresh_button = QToolButton()
        refresh_button.setText(tr("button_refresh", "刷新"))
        refresh_button.setToolTip(tr("tooltip_refresh_history", "刷新查询历史"))
        refresh_button.clicked.connect(self.refresh)
        
        # 清空按钮
        clear_button = QToolButton()
        clear_button.setText(tr("button_clear", "清空"))
        clear_button.setToolTip(tr("tooltip_clear_history", "清空查询历史"))
        clear_button.clicked.connect(self._clear_history)
        
        title_layout.addStretch()
        title_layout.addWidget(refresh_button)
        title_layout.addWidget(clear_button)
        
        # 设置标题栏布局的大小策略，使其高度适应内容
        title_widget = QWidget()
        title_widget.setLayout(title_layout)
        title_widget.setFixedHeight(refresh_button.sizeHint().height())
        
        layout.addWidget(title_widget)
        
        # 列表控件
        self.list_widget = QListWidget()
        self.list_widget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.list_widget.customContextMenuRequested.connect(self._show_context_menu)
        self.list_widget.itemDoubleClicked.connect(self._handle_item_double_clicked)
        
        layout.addWidget(self.list_widget)
        
        # 查询详情查看
        preview_layout = QVBoxLayout()
        preview_label = QLabel(tr("label_query_preview", "查询预览"))
        
        self.preview_text = QTextEdit()
        self.preview_text.setReadOnly(True)
        self.preview_text.setMaximumHeight(100)
        
        preview_layout.addWidget(preview_label)
        preview_layout.addWidget(self.preview_text)
        
        layout.addLayout(preview_layout)
        
        # 加载历史
        self.refresh()
        
        # 连接信号
        self.list_widget.currentItemChanged.connect(self._update_preview)
        
    def refresh(self):
        """刷新查询历史"""
        self.list_widget.clear()
        
        # 获取查询历史
        history = self.query_manager.get_query_history()
        
        for item in history:
            list_item = QListWidgetItem(self.list_widget)
            
            # 设置显示文本
            query_text = item["query_text"]
            time_str = item.get("formatted_time", "")
            
            # 截断查询文本
            if len(query_text) > 50:
                display_text = query_text[:47] + "..."
            else:
                display_text = query_text
                
            # 移除换行
            display_text = display_text.replace("\n", " ")
            
            list_item.setText(f"{display_text}")
            list_item.setToolTip(f"{time_str}\n{query_text}")
            
            # 存储原始数据
            list_item.setData(Qt.UserRole, item)
            
            # 设置颜色
            if not item.get("success", True):
                list_item.setForeground(QColor("#cc0000"))  # 失败为红色
                
        if self.list_widget.count() > 0:
            self.list_widget.setCurrentRow(0)
            
    def _update_preview(self, current, previous):
        """更新查询预览
        
        Args:
            current: 当前项
            previous: 上一项
        """
        if not current:
            self.preview_text.clear()
            return
            
        item_data = current.data(Qt.UserRole)
        if not item_data:
            return
            
        query_text = item_data.get("query_text", "")
        self.preview_text.setPlainText(query_text)
        
        # 发出选中信号
        self.query_selected.emit(query_text)
        
    def _show_context_menu(self, position):
        """显示上下文菜单
        
        Args:
            position: 鼠标位置
        """
        item = self.list_widget.itemAt(position)
        if not item:
            return
            
        menu = QMenu(self)
        
        # 执行查询操作
        execute_action = QAction(tr("action_execute_query_context", "执行查询"), self)
        execute_action.triggered.connect(lambda: self._execute_selected_query(item))
        
        # 复制查询操作
        copy_action = QAction(tr("action_copy_query", "复制查询"), self)
        copy_action.triggered.connect(lambda: self._copy_selected_query(item))
        
        menu.addAction(execute_action)
        menu.addAction(copy_action)
        
        menu.exec_(self.list_widget.viewport().mapToGlobal(position))
        
    def _handle_item_double_clicked(self, item):
        """处理项目双击事件
        
        Args:
            item: 点击的项目
        """
        self._execute_selected_query(item)
        
    def _execute_selected_query(self, item):
        """执行选中的查询
        
        Args:
            item: 选中的项目
        """
        item_data = item.data(Qt.UserRole)
        if not item_data:
            return
            
        query_text = item_data.get("query_text", "")
        self.query_executed.emit(query_text)
        
    def _copy_selected_query(self, item):
        """复制选中的查询
        
        Args:
            item: 选中的项目
        """
        item_data = item.data(Qt.UserRole)
        if not item_data:
            return
            
        query_text = item_data.get("query_text", "")
        
        # 复制到剪贴板
        from PySide6.QtGui import QGuiApplication
        clipboard = QGuiApplication.clipboard()
        clipboard.setText(query_text)
        
        # 发出复制信号
        self.query_copied.emit(query_text)
        
    def _clear_history(self):
        """清空查询历史"""
        reply = QMessageBox.question(
            self, 
            tr("confirm_clear_query_history", "确认清空查询历史"), 
            tr("confirm_clear_query_history_message", "确定要清空所有查询历史记录吗？\n此操作不可撤销。"), 
            QMessageBox.Yes | QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            self.query_manager.clear_query_history()
            self.refresh() 